package com.lzq.model.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : modify
 * @version : v1.0
 * @description :
 * @createTime : 2022/11/28 20:15
 * @updateUser : modify
 * @updateTime : 2022/11/28 20:15
 * @updateRemark : 观察者模式
 */
public interface Observer {
    /**
     * 更新内容
     *
     * @param message
     */
    void update(String message);
}

interface Subject {
    /**
     * 增加订阅者
     *
     * @param observer
     */
    public void attach(Observer observer);

    /**
     * 删除订阅者
     *
     * @param observer
     */
    public void detach(Observer observer);

    /**
     * 通知订阅者更新消息
     *
     * @param message
     */
    public void notify(String message);
}

class SubscriptionSubject implements Subject {

    private List<Observer> observerList = new ArrayList<Observer>();

    @Override
    public void attach(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notify(String message) {
        for (Observer observer : observerList) {
            observer.update(message);
        }
    }
}

class User implements Observer {
    private String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public void update(String message) {
        System.out.println(name + " | " + message);
    }
}

class Test {
    public static void main(String[] args) {
        SubscriptionSubject subscriptionSubject = new SubscriptionSubject();
        User user1 = new User("黄月");
        User user2 = new User("黄月月");
        User user3 = new User("黄月月鸟");

        subscriptionSubject.attach(user1);
        subscriptionSubject.attach(user2);
        subscriptionSubject.attach(user3);

        subscriptionSubject.notify("send one message");
    }
}